package com.gjm.demo.controller;

import com.gjm.demo.service.UserInfoService;
import org.apache.ibatis.annotations.Insert;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * 编程式事务
 */
@RestController
@RequestMapping("/user")
public class UserInfoController {

    /**
     * 事务管理器
     */
    @Autowired
    private DataSourceTransactionManager dataSourceTransactionManager;

    @Autowired
    private TransactionDefinition transactionDefinition;

    @Autowired
    private UserInfoService userInfoService;

    @RequestMapping("/registry")
    public String insertUserInfo(String username, String password) {

        //开启事务
        TransactionStatus transaction = dataSourceTransactionManager.getTransaction(transactionDefinition);//保存当前事务

        //用户注册
        Integer result = userInfoService.insertUserInfo(username, password);

//        //事务提交
//        dataSourceTransactionManager.commit(transaction);

        //事务回滚，不能与事务提交同时存在
        dataSourceTransactionManager.rollback(transaction);

        return "插入成功";
    }
}
